package com.chen.timeconvertor;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.wm.WindowManager;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

/**
 * @author chenxubing
 * @version $Id: ConvertorAction.java, v 0.1 2018-11-28 9:25 AM chenxubing Exp $$
 */
public class Date2LongFrame extends JFrame{
  private static final int FRAME_WIDTH = 450;
  private static final int FRAME_HEIGHT = 150;
  private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

  private Project project;
  Date2LongFrame(Project project){
    this.project = project;
  }

  public void init() {
    Font font = new Font("宋体", 1, 14);

    GridLayout gridLayOut = new GridLayout();
    gridLayOut.setColumns(2);
    gridLayOut.setRows(2);
    gridLayOut.setVgap(8);
    this.setLayout(gridLayOut);

    JTextField textLong = new JTextField();
    textLong.setFont(font);
    textLong.setText(System.currentTimeMillis() + "");

    JTextField textDate = new JTextField();
    textDate.setFont(font);
    textDate.setText(DATE_FORMAT.format(new Date()));

    JButton btn2long = new JButton();
    btn2long.setText("转为毫秒");
    btn2long.setFont(font);
    btn2long.addActionListener((event)->{
      try {
        String strDate = textDate.getText();
        long longVal = DATE_FORMAT.parse(strDate).getTime();
        textLong.setText(longVal + "");
      } catch (Exception e) {
        Messages.showMessageDialog(Date2LongFrame.this, "出错了", "出错了", Messages.getInformationIcon());
      }
    });

    JButton btn2date = new JButton();
    btn2date.setText("转为日期");
    btn2date.setFont(font);
    btn2date.addActionListener((event) -> {
        try {
          String strLong = textLong.getText();
          String strDate = DATE_FORMAT.format(new Date(Long.parseLong(strLong)));
          textDate.setText(strDate);
        } catch (Exception e) {
          Messages.showMessageDialog(Date2LongFrame.this, "出错了", "出错了", Messages.getInformationIcon());
        }
    });

    add(textLong);
    add(btn2date);
    add(textDate);
    add(btn2long);

    this.setTitle("日期转换");
    this.setSize(Date2LongFrame.FRAME_WIDTH, Date2LongFrame.FRAME_HEIGHT);
    this.setResizable(false);
    this.setVisible(true);
    Window window = WindowManager.getInstance().suggestParentWindow(project);
    this.setLocationRelativeTo(window);
  }
}